package com.lizemin.websocketclient.controller;

import com.lizemin.websocketclient.handler.SimpleWebSocketClientHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.client.WebSocketConnectionManager;

import java.io.IOException;

@RestController
public class WebSocketClientController {

    private static final Logger log = LoggerFactory.getLogger(WebSocketClientController.class);

    /**
     * WebSocket 连接管理器
     */
    @Autowired
    private WebSocketConnectionManager connectionManager;

    /**
     * WebSocket 客户端处理器
     */
    @Autowired
    private SimpleWebSocketClientHandler simpleWebSocketClientHandler;

    /**
     * 给服务端发送消息
     *
     * @param message 消息内容
     * @throws IOException IO异常
     */
    @GetMapping("/send")
    public void sendMessage(String message) throws IOException {
        simpleWebSocketClientHandler.sendMessage(message);
    }

    /**
     * 重连上websocket服务端
     */
    @GetMapping("/reconnect")
    public void reconnect() {
        log.info("开始重连websocket服务器");
        if (connectionManager.isRunning()) {
            connectionManager.stop();
        }
        connectionManager.start();
    }

    /**
     * 断开和websocket服务端之间的连接
     */
    @GetMapping("/disconnect")
    public void disconnect() {
        log.info("开始断开和websocket服务器之间的连接");
        if (connectionManager.isRunning()) {
            connectionManager.stop();
        }
    }

}